package org.lansir.af.database;

import java.util.Vector;

import org.lansir.af.R;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

/**
 * 
 * @author 蓝智宏
 *
 */
public class Database {
	public static final String TAG = "Database";
	// types
	public enum Result {
		Success, errUnknown, errCantInsertNewData, errCantUpdateData, errCantCreateTable, errNoDbAccess, errCantGetDataFromTable, errCantFindData, errCantGetData, errCantDeleteData, errTableNotExists, errCantSetValuesForDataRow, errCantGetValuesFromDataRow,
	};

	// fields
	public static final String sTableNameActivities = "Activities";
	public static final String sTableNameAlarms = "Alarms";
	public static final String sTableNameGroups = "Groups";
	public static final String sTableNameGroupMembers = "GroupMembers";
	public static final String sTableNameActivityParticipator = "ActivityParticipator";
	public static final String sTableNameTrustys = "Trustys";

	// fields
	public static final String dbName = "ActivityFairy.db";
	private Context ctx = null;
	private SQLiteDatabase db = null;
	private Result resultDbTablesCreated = Result.errUnknown;

	// methods
	public Database(Context context) {
		ctx = context;
		if(open())
			createTables();
	}

	public final String getName() {
		return dbName;
	}

	public static int getErrDesc(Result result) {
		int msgId = R.string.errUnknown;
		if (result == Result.errCantInsertNewData)
			msgId = R.string.errCantInsertNewData;
		if (result == Result.errCantUpdateData)
			msgId = R.string.errCantUpdateData;
		if (result == Result.errCantCreateTable)
			msgId = R.string.errCantCreateTable;
		if (result == Result.errNoDbAccess)
			msgId = R.string.errNoDbAccess;
		if (result == Result.errCantGetDataFromTable)
			msgId = R.string.errCantGetDataFromTable;
		if (result == Result.errCantFindData)
			msgId = R.string.errCantFindData;
		if (result == Result.errCantGetData)
			msgId = R.string.errCantGetData;
		if (result == Result.errCantDeleteData)
			msgId = R.string.errCantDeleteData;
		if (result == Result.errTableNotExists)
			msgId = R.string.errTableNotExists;
		if (result == Result.errCantSetValuesForDataRow)
			msgId = R.string.errCantSetValuesForDataRow;
		if (result == Result.errCantGetValuesFromDataRow)
			msgId = R.string.errCantGetValuesFromDataRow;
		return msgId;
	}

	public boolean open() {
		boolean bSuccess = false;
		// open / create database
		
		db = ctx.openOrCreateDatabase(dbName, Context.MODE_PRIVATE, null);
		
		// test result
		if (isOpened()) {
			bSuccess = true;
			
		} else {
			db = null;
		}
		return bSuccess;
	}

	public void close() {
		if (isOpened()){
			db.close();
			db = null;
	
		}
	}

	public boolean isOpened() {
		if (db != null)
			return db.isOpen();
		return false;
	}

	public SQLiteDatabase getSQLiteDb() {
		return db;
	}

	public boolean delete() {
		close();
		return ctx.deleteDatabase(dbName);
	}

	public boolean execSQL(String sql) {
		boolean bSuccess = false;
		try {
			if (isOpened())
				db.execSQL(sql);
			bSuccess = true;
		} catch (SQLException e) {
		}
		return bSuccess;
	}

	public boolean tableExists(String sTableName) {
		boolean bResult = false;
		if (isOpened()) {
			String sql = "select name from sqlite_master where type = 'table' and name = '%s'";
			sql = String.format(sql, sTableName);
			Cursor cr = db.rawQuery(sql, null);
			if (cr.getCount() > 0)
				bResult = true;
			cr.close();
		}
		return bResult;
	}

	// 创建各种数据表
	private void createTables() {
		resultDbTablesCreated = Database.Result.errUnknown;
		if (isOpened()) {
			Vector<DataRow> vecDataRows = new Vector<DataRow>();
			vecDataRows.add(new DataRowActivity(this));
			vecDataRows.add(new DataRowAlarm(this));
			vecDataRows.add(new DataRowActivityParticipator(this));
			vecDataRows.add(new DataRowTrusty(this));

			for (int i = 0; i < vecDataRows.size(); i++) {
				DataTable dataTable = new DataTable(vecDataRows.get(i));
				if (dataTable.createTable()) {
					resultDbTablesCreated = Database.Result.Success;
				} else {
					resultDbTablesCreated = Database.Result.errCantCreateTable;
					break;
				}
			}
		} else {
			resultDbTablesCreated = Database.Result.errNoDbAccess;
		}
	}

	public boolean tablesCreated() {
		return resultDbTablesCreated == Result.Success;
	}

	public synchronized boolean databaseReady() {
		return (isOpened() && tablesCreated());
	}

	public Result tablesCreationResult() {
		return resultDbTablesCreated;
	}
	

	@Override
	public void finalize() {
		if(db != null)
			db.close();

	}
	

}
